<template>
	<div>
		<el-card class="box-card">
			<div class=" flex_row">
				<div class="flex_row" style="width: 500px;align-items: center;">
						<span style="width: 80px;">模板名称：</span>
						<el-input v-model="templateForm.name" clearable style="width: 100%;" size="mini" placeholder="请输入模板名称" />
				</div>
				<el-button type="primary" @click="sumbit" >提交</el-button>
			</div>
		</el-card>
		<el-collapse v-model="activeName" class="box-card" v-for="(item,idx) in templateForm.details">
			<el-collapse-item :name="item.indicatorStatus">
				<template slot="title">
					<div class="flex_row title">
						<div>{{$store.getters.getIndicatorType[item.indicatorStatus]}}
							<el-button type="primary" v-if="item.indicatorStatus=='ACQUIESCE'" icon="el-icon-plus" plain @click.stop="addIndicatorType">添加指标类别</el-button>
						</div>
						<div class="flex_row">
							<span class="icon_normal" @click.stop="addIndicator(item,idx)">添加指标</span>
							<span class="icon_warning" @click.stop="operate('clean',idx)">清空</span>
							<span class="icon_error" @click.stop="operate('del',idx)" v-if="item.indicatorStatus!='ACQUIESCE'">删除</span>
						</div>
					</div>
				</template>
				<div class="indicator_box" :style="getHeight()">
					<el-table :data="item.entryList" :key="tableKey" :class="item.indicatorStatus+'-table'" row-key="indicatorLibraryCode" height="100%" border :cell-style="{ padding: '3px' }"
						:header-cell-style="{ backgroundColor:'#f4f4f4',textAlign:'center' }" style="width: 100%;position: absolute;">
						<el-table-column align="center" width="40" >
							<template>
								<i class="el-icon-s-operation sortable"></i>
							</template>
						</el-table-column>
						<el-table-column type="index" label="序号" align="center" width="50" />
						<el-table-column prop="indicatorGroupName" align="center" label="指标分组" width="180" />
						<el-table-column prop="indicatorLibraryName" align="center" label="指标名称" width="180" >
							<template slot-scope="{row,$index}">
								<span v-if="row.editStatus">
									<el-input v-model="row.indicatorLibraryName" clearable class="my_input" size="mini"
										placeholder="请输入指标名称" />
								</span>
								<span v-else>{{row.indicatorLibraryName}}</span>
							</template>
						</el-table-column>
						<el-table-column prop="indicatorLibraryRemark" align="center" label="指标描述" min-width="300" >
							<template slot-scope="{row,$index}">
								<span v-if="row.editStatus">
									<el-input v-model="row.indicatorLibraryRemark" type="textarea" :autosize="{ minRows: 2, maxRows: 10}" clearable style="width: 100%;" size="mini"
										placeholder="请输入指标描述" />
								</span>
								<span v-else>{{row.indicatorLibraryRemark}}</span>
							</template>
						</el-table-column>
						<el-table-column prop="assessStandardRemark" align="center" label="考核标准"  min-width="300" >
							<template slot-scope="{row,$index}">
								<span v-if="row.editStatus">
									<el-input v-model="row.assessStandardRemark" type="textarea" :autosize="{ minRows: 2, maxRows: 10}" clearable style="width: 100%;" size="mini"
										placeholder="请输入考核标准" />
								</span>
								<span v-else>{{row.assessStandardRemark}}</span>
							</template>
						</el-table-column>	
						<el-table-column prop="assessScoringRules" align="center" label="计分规则" min-width="300" >
							<template slot-scope="{row,$index}">
								<span v-if="row.editStatus">
									<el-input v-model="row.assessScoringRules" type="textarea"  :autosize="{ minRows: 2, maxRows: 10}" clearable style="width: 100%;" size="mini"
										placeholder="请输入计分规则" />
								</span>
								<span v-else>{{row.assessScoringRules}}</span>
							</template>
						</el-table-column>	
						<el-table-column label="操作" width="100" align="center" fixed="right">
							<template slot-scope="{row,$index}">
								<i v-if="row.editStatus" class="iconfont icon_warning icon-a-queren" title="确认" @click="operate('edit',$index, row)" />
								<i v-else class="iconfont icon_warning icon-a-xiugai" title="修改" @click="operate('edit',$index, row)" />
								<i class="iconfont icon_error icon-a-shanchu" title="删除" @click="operate('del',$index,item.entryList)" />
							</template>
						</el-table-column>
					</el-table>
				</div>
			</el-collapse-item>
		</el-collapse>

		<!-- 指标类别 -->
		<el-dialog title="指标类别" custom-class="my_dialog" :visible.sync="visibleIndicatorType" width="400px">
			<div class="dialog-box">
				<el-checkbox-group v-model="indicatorType" size="medium">
					<el-checkbox :label="item.indicatorStatus" :key="item.indicatorStatus" :disabled=item.disabled
						v-for="item in indicatorTypeList">{{item.indicatorStatusName}}</el-checkbox>
				</el-checkbox-group>
			</div>
			<div slot="footer" class="dialog-footer">
				<el-button size="mini" @click="handleClose('indicatorType')">取 消</el-button>
				<el-button size="mini" type="primary" @click="dialogSure('indicatorType')">确 定</el-button>
			</div>
		</el-dialog>

		<!-- 指标 -->
		<el-dialog title="添加指标" custom-class="my_dialog" top="8vh" :visible.sync="visibleIndicator" width="80%">
			<div style="height:600px">
				<indicatorLibrary v-if="visibleIndicator" ref="indicatorLibrary" isCheckDialog :reserveSelection="reserveSelection"
					@selectionChange="selectionChange" />
			</div>
			<div slot="footer" class="dialog-footer">
				<el-button size="mini" @click="handleClose('indicator')">取 消</el-button>
				<el-button size="mini" type="primary" @click="dialogSure('indicator')">确 定</el-button>
			</div>
		</el-dialog>

	</div>
</template>
<script>
	import {
		Switch
	} from 'vant'
	import indicatorLibrary from '../indicatorLibrary.vue'
	import Sortable from "sortablejs";
	export default {
		name:'templateDetails',
		components: {
			indicatorLibrary,
		},
		data() {
			return {
				templateForm:{
					name:'',
					details: [],
				},
				isDetails:false, // 新增/详情
				tableKey:false,
				addIndicatorIdx: 0, // 指标类别序号
				reserveSelection: [], // 已选指标类别下的指标
				selectionList: [],
				activeName: ['ACQUIESCE', 'POINTS'],
				indicatorTypeList: [],
				visibleIndicatorType: false,
				visibleIndicator: false,
				indicatorType: [], //指标类别复选框

				groupList: [{
					name: 'IT组',
					id: 1
				}], // 指标分组下拉框
				tableList: [{
					name: '指标1',
					groupId: 1,
					groupName: 'IT组',
					desc: '指标描述',
				}], // 指标库列表
				searchForm: {
					current: 1,
					size: this.$defaultPage,
					groupId: '', // 指标分组
				},
				total: 0,
				isSumbitFinish:false,
			}
		},
	
		created() {
			// 获取数据
			this.init()
		
			
		},
		
		methods: {
			// 表格行拖拽
			initSortable(){
				setTimeout(()=>{
					// 需要支持拖动效果的列表容器，在这里我们设置为el-table组件的tbody，
					// 注意：最前面的一段为前面el-table的class: draggable-table，主要为了防止如果页面有多个table，多个table同时实现拖拽效果
					// 当然，如果多个table都需要拖拽效果，选择器中最前面的.draggable-table可以去除。
					const tbody = document.querySelectorAll(".el-table__body-wrapper tbody");
					tbody.forEach((item,idx)=>{
						new Sortable(item, {
						  animation: 150,
							handle:'.sortable',
						  // 需要在odEnd方法中处理原始eltable数据，使原始数据与显示数据保持顺序一致
						  onEnd: ({ newIndex, oldIndex }) => {
						    const targetRow = this.templateForm.details[idx].entryList[oldIndex];
						    this.templateForm.details[idx].entryList.splice(oldIndex, 1);
						    this.templateForm.details[idx].entryList.splice(newIndex, 0, targetRow);
						    // console.table(this.templateForm.details[idx].entryList);
						  },
						}); 
					})
				},500)
				
				
			},		 
			init(){
				// this.indicatorTypeList = this.$store.getters.getIndicatorType
				this.indicatorTypeList=[]
				this.activeName=[]
				Object.keys(this.$store.getters.getIndicatorType).forEach(key => {
					this.activeName.push(key)
					this.indicatorTypeList.push({
						indicatorStatusName:this.$store.getters.getIndicatorType[key],
						indicatorStatus:key
					})
				});
				this.templateForm.details = [{
					indicatorStatus:this.indicatorTypeList[0].indicatorStatus,
					indicatorStatusName:this.indicatorTypeList[0].indicatorStatusName,
					entryList:[]
				}]
		
				this.getHeight()
				this.getParam()
			},
			checkData() {
				let status = false
				this.templateForm.details.some((item, idx) => {
					if(item.entryList.length==0){
						this.$message.warning(this.$store.getters.getIndicatorType[item.indicatorStatus]+'不能为空')
						status = true
						return true
						this.$store.getters.getIndicatorType[item.indicatorStatus]
					}
					item.entryList.some((item2, idx2) => {
						if(status){
							return true
						}
						if (item2.indicatorLibraryRemark =='') {
							this.$message.warning('指标描述不能为空')
							status = true
							return true
						}
						if (item2.assessStandardRemark =='') {
							this.$message.warning('考核标准不能为空')
							status = true
							return true
						}
						if (item2.assessScoringRules =='') {
							this.$message.warning('计分规则不能为空')
							status = true
							return true
						}
					})
				})
				return status
			},
			sumbit(){
				if(this.templateForm.name==''){
					this.$message.warning('请输入考核模板名称')
					return true
				}
				if(this.checkData()){
					return 
				}
				let arr=this.$uDeepClone(this.templateForm.details)
				let details=[]
				arr.forEach((item,idx)=>{
					item.entryList.forEach((item2,idx2)=>{
						item2.sort=idx2
						item2.indicatorStatus=item.indicatorStatus
						details.push(item2)
					})
				})
				let obj=this.$uDeepClone(this.templateForm)
				obj.details=details
				this.$API.assessTemplate.reqCreate(obj).then((res)=>{
					if(res.code=='0'){
						this.isSumbitFinish=true
						this.$message.success('操作成功')
						// 删除当前页
						this.$store.dispatch("delVisitedViews", this.$route);
						// 删除考核模板列表缓存
						this.$store.dispatch('delKeepViews','assessmentTemplate')
						
						let url='/performanceSystem/assessmentManagement/assessmentTemplate'
						setTimeout(()=>{
							// 删除考核模板列表
							this.$store.dispatch('delVisitedViews', {path:url})
							// 跳转考核模板列表
							this.$goPage({ path: url})
						},500)
						
					}else{
						this.$message.error(res.masg)
					}
				})
			},
			// 解析路由参数
			getParam() {
			  const query = this.$route.query
				let res = query ? this.$decode(query) : ''
				if(res.code){
					this.isDetails=true
					this.getDetials(res.code)
				}
			},
			initArr(arr) {
				arr.some((item, idx) => {
					if (item.indicatorStatus == 'ACQUIESCE') {
						arr.unshift(arr.splice(idx, 1)[0])
						return true
					}
				})
				return arr
			},
			// 获取详情数据
			getDetials(code) {
			  this.$API.assessTemplate.reqDetail(code).then((res)=>{
					if(res.code=='0'){
						let arr=[]
						res.responseBody.details.forEach(item=>{
							arr.push({
								indicatorStatus:item[0].indicatorStatus,
								indicatorStatusName:this.indicatorTypeList[item[0].indicatorStatus],
								entryList:item
							})
						
						})
						this.templateForm=res.responseBody
						this.templateForm.details=this.initArr(arr)
						this.initSortable()
					
					}else{
						this.$message.error(res.masg)
					}
				})
			},
			
			// 指标选择
			selectionChange(e) {
				let arr = this.$uDeepClone(e)
				arr.forEach(item => {
					item.scoreWeight = 0
					item.score = 0
				})
				this.selectionList = arr
			},
			// 获取table高度
			getHeight() {
				let style = ''
				let len = this.templateForm.details.length
				let height = 240
				if (len == 2) {
					height = 623
				}
				if (len > 2) {
					height = this.templateForm.details.length * 200
				}
				style = 'height:calc(100vh - ' + height + 'px);'
				return style
			},
			// 一键分配
			allocation(idx) {
				let data = this.templateForm.details[idx]
				let num1 = Math.floor(data.scoreWeight / data.entryList.length)
				let num2 = data.scoreWeight - (num1 * (data.entryList.length - 1))
				data.entryList.forEach((item, idx) => {
					item.scoreWeight = idx == 0 ? num2 : num1
				})

			},
			// 添加指标类型
			addIndicatorType() {
				this.indicatorType = []
				this.indicatorTypeList.forEach((item, idx) => {
					item.disabled = false
					this.templateForm.details.some((item2, idx2) => {
						if (item.indicatorStatus == item2.indicatorStatus) {
							item.disabled = true
							return true
						}
					})
				})
				this.visibleIndicatorType = true
			},

			// 添加指标
			addIndicator(data, idx) {
				this.visibleIndicator = true
				this.addIndicatorIdx = idx
				let arr = []
				this.templateForm.details.forEach((item, idx) => {
					arr = arr.concat(item.entryList || [])
				})
				this.reserveSelection = arr
				
			},

			// 添加指标/指标类型 确认事件
			dialogSure(type) {
				switch (type) {
					case 'indicatorType':
						this.indicatorType.forEach((item, idx) => {
							this.indicatorTypeList.some((item2, idx2) => {
								if (item == item2.indicatorStatus) {
									this.templateForm.details.push(item2)
									return true
								}
							})
						})
						this.visibleIndicatorType = false
						break;
					case 'indicator':
						let arr = (this.templateForm.details[this.addIndicatorIdx]).entryList || []
						let arr2=[]
						this.selectionList.forEach(item=>{
							arr2.push({
								assessTemplateSystemCode:item.assessTemplateSystemCode,
								indicatorGroupSystemCode:item.indicatorGroupSystemCode,
								indicatorGroupName:item.indicatorGroupName,
								indicatorLibraryCode:item.code,
								indicatorLibraryName:item.name,
								indicatorLibraryRemark:item.remark,
								assessStandardRemark:item.standardRemark,
								indicatorStatus:item.indicatorStatus,
								assessScoringRules:item.scoringRules,
								editStatus:true
							})
						
						})
						this.templateForm.details[this.addIndicatorIdx].entryList = arr.concat(arr2)
						this.tableKey=!this.tableKey
						this.visibleIndicator = false
						this.initSortable()
						break;
				}
			},

			// 取消按钮
			handleClose(type) {
				switch (type) {
					case 'indicatorType':
						this.visibleIndicatorType = false
						break;
					case 'indicator':
						this.visibleIndicator = false
						break;
				}
			},


			
			// 获取列表数据
			async searchOne(val) {
				let res = await this.$API.activeManage.reqSearchOne(val)
				let {
					code,
					responseBody
				} = res
				if (code == 0) {
					this.tableList = responseBody.records || []
					this.total = Number(responseBody.total)
				}
			},
		
			
			// 内部方法
			async operate(type,idx,item) {
				switch (type) {
					case 'edit': // 编辑
						this.$set(item,'editStatus',!item.editStatus)
						break
					case 'del':
						this.$confirm('是否确定删除？', '提示', {
							confirmButtonText: '确定',
							cancelButtonText: '取消',
							type: '',
							customClass: 'my_confirm'
						}).then(() => {
							if (item) {
								item.splice(idx, 1)
							} else {
								this.templateForm.details.splice(idx, 1)
							}
							// this.searchOne(this.searchForm)
						})
						break
					case 'clean':
						this.$confirm('是否确定清空？', '提示', {
							confirmButtonText: '确定',
							cancelButtonText: '取消',
							type: '',
							customClass: 'my_confirm'
						}).then(() => {
							this.templateForm.details[idx].entryList=[]
						})
						break
				}
			},


			
		}
	}
</script>

<style lang="scss" scoped>
	.box-card {
		background-color: #fff;
		margin: 10px 10px 0 10px;
		padding: 12px;

		.title {
			font-size: 15px;
			width: 100%;
			font-weight: bold;

			div:nth-child(1) {
				color: #006ee3;
			}
		}
	}

	.my_input {
		max-width: 300px;
		margin-right: 15px;
	}

	::v-deep .el-collapse-item__header,
	::v-deep .el-collapse-item__wrap {
		border: none;
	}
	
	
	::v-deep .el-collapse-item__content {
		padding-bottom: 0;
	}

	::v-deep .el-checkbox__label {
		line-height: 30px;
		font-size: 14px;
	}

	.main {
		margin-bottom: 10px;

		::v-deep th {
			height: 20px;
			padding: 1px;
		}
	}

	.dialog-box {
		padding: 10px 100px;
		margin-top: 20px;
	}

	.ann_input {
		width: 300px;
	}

	.indicator_box {
		min-height: 260px;
		position: relative;
	}
</style>